<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

// 响应式数据
const users = ref([])
const files = ref([])
const showProgress = ref(false)
const progress = ref(0)
const websocket = ref(null)
const activeMenu = ref('users') // 当前激活的菜单
const selectedFile = ref(null)
const uploadProgress = ref(0)
const uploadMessage = ref('')
const showUploadMessage = ref(false)
const messageType = ref('success') // 'success' | 'error' | 'warning'

// OSS下载上传相关
const ossUrl = ref('')
const ossUploadProgress = ref(0)
const ossUploadMessage = ref('')
const showOssUploadMessage = ref(false)
const ossMessageType = ref('success')

onMounted(async () => {
  await loadUsers()
  await loadFiles()
})

onUnmounted(() => {
  closeWebSocket()
})

// 加载用户数据
const loadUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/users')
    users.value = response.data
  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

// 加载文件列表
const loadFiles = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/files/list')
    files.value = response.data || []
  } catch (error) {
    console.error('获取文件列表失败:', error)
  }
}

// 文件上传
const handleFileUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查文件大小 (10MB)
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    showMessage('文件过大', `文件大小不能超过10MB，当前文件大小: ${formatFileSize(file.size)}`, 'error')
    event.target.value = ''
    return
  }
  
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    uploadProgress.value = 0
    showUploadMessage.value = false
    
    const response = await axios.post('http://localhost:8080/api/files/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
      }
    })
    
    if (response.status === 200) {
      const result = response.data
      if (result.success) {
        showMessage('上传成功', result.message, 'success')
        await loadFiles() // 重新加载文件列表
      } else {
        showMessage('上传失败', result.message || '未知错误', 'error')
      }
    }
    
    uploadProgress.value = 0
    event.target.value = '' // 清空文件选择
  } catch (error) {
    console.error('文件上传失败:', error)
    uploadProgress.value = 0
    
    // 处理错误响应
    if (error.response && error.response.data) {
      const errorData = error.response.data
      showMessage(errorData.error || '上传失败', errorData.message || '文件上传失败', 'error')
    } else {
      showMessage('网络错误', '无法连接到服务器，请检查网络连接', 'error')
    }
    
    event.target.value = ''
  }
}

// OSS下载并上传
const handleOssDownloadUpload = async () => {
  if (!ossUrl.value.trim()) {
    showOssMessage('参数错误', '请输入OSS资源地址', 'error')
    return
  }
  
  try {
    ossUploadProgress.value = 0
    showOssUploadMessage.value = false
    
    // 模拟进度（实际进度由后端控制）
    const progressInterval = setInterval(() => {
      if (ossUploadProgress.value < 90) {
        ossUploadProgress.value += 10
      }
    }, 200)
    
    const response = await axios.post('http://localhost:8080/api/files/oss-download-upload', {
      url: ossUrl.value.trim()
    })
    
    clearInterval(progressInterval)
    ossUploadProgress.value = 100
    
    if (response.status === 200) {
      const result = response.data
      if (result.success) {
        showOssMessage('操作成功', result.message, 'success')
        ossUrl.value = '' // 清空输入框
        await loadFiles() // 重新加载文件列表
      } else {
        showOssMessage('操作失败', result.message || '未知错误', 'error')
      }
    }
    
    setTimeout(() => {
      ossUploadProgress.value = 0
    }, 1000)
  } catch (error) {
    console.error('OSS下载上传失败:', error)
    ossUploadProgress.value = 0
    
    // 处理错误响应
    if (error.response && error.response.data) {
      const errorData = error.response.data
      showOssMessage(errorData.error || '操作失败', errorData.message || '下载并上传失败', 'error')
    } else {
      showOssMessage('网络错误', '无法连接到服务器，请检查网络连接', 'error')
    }
  }
}

// 显示OSS操作消息
const showOssMessage = (title, message, type = 'success') => {
  ossUploadMessage.value = `${title}: ${message}`
  ossMessageType.value = type
  showOssUploadMessage.value = true
  
  // 3秒后自动隐藏
  setTimeout(() => {
    showOssUploadMessage.value = false
  }, 3000)
}

// 删除文件
const deleteFile = async (fileName) => {
  if (!confirm('确定要删除这个文件吗？')) return
  
  try {
    await axios.delete(`http://localhost:8080/api/files/${encodeURIComponent(fileName)}`)
    await loadFiles() // 重新加载文件列表
  } catch (error) {
    console.error('删除文件失败:', error)
  }
}

// 下载文件
const downloadFile = async (fileName) => {
  try {
    const res = await axios.get(`http://localhost:8080/api/files/download-url/${encodeURIComponent(fileName)}`)
    if (res.data.url) {
      window.open(res.data.url, '_blank')
    } else {
      showMessage('下载失败', res.data.message || '无法获取下载链接', 'error')
    }
  } catch (e) {
    showMessage('下载失败', e.response?.data?.message || '无法获取下载链接', 'error')
  }
}

// 切换菜单
const switchMenu = (menu) => {
  activeMenu.value = menu
}

const exportUsers = () => {
  window.open('http://localhost:8080/api/users/export', '_blank')
}

const startProgress = async () => {
  // 重置进度
  progress.value = 0
  showProgress.value = true
  
  // 连接WebSocket
  connectWebSocket()
  
  // 调用后端API启动进度模拟
  try {
    await axios.post('http://localhost:8080/api/progress/start')
  } catch (error) {
    console.error('启动进度模拟失败:', error)
  }
}

const connectWebSocket = () => {
  // 关闭已有连接
  closeWebSocket()
  
  // 创建新连接
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  // 使用后端服务器地址，假设后端运行在8080端口
  const wsUrl = `${wsProtocol}//localhost:8080/ws/progress`
  
  websocket.value = new WebSocket(wsUrl)
  
  websocket.value.onmessage = (event) => {
    // 更新进度
    progress.value = parseInt(event.data)
    
    // 进度完成后关闭连接
    if (progress.value >= 100) {
      setTimeout(() => {
        showProgress.value = false
        closeWebSocket()
      }, 1000)
    }
  }
  
  websocket.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }
}

const closeWebSocket = () => {
  if (websocket.value && websocket.value.readyState !== WebSocket.CLOSED) {
    websocket.value.close()
  }
  websocket.value = null
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 显示消息提示
const showMessage = (title, message, type = 'success') => {
  uploadMessage.value = `${title}: ${message}`
  messageType.value = type
  showUploadMessage.value = true
  
  // 3秒后自动隐藏
  setTimeout(() => {
    showUploadMessage.value = false
  }, 3000)
}
</script>

<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>管理系统</h2>
      </div>
      <nav class="sidebar-nav">
        <div 
          class="nav-item" 
          :class="{ active: activeMenu === 'users' }"
          @click="switchMenu('users')"
        >
          <span class="nav-icon">👥</span>
          <span>用户管理</span>
        </div>
        <div 
          class="nav-item" 
          :class="{ active: activeMenu === 'files' }"
          @click="switchMenu('files')"
        >
          <span class="nav-icon">📁</span>
          <span>文件管理</span>
        </div>
      </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 用户管理页面 -->
      <div v-if="activeMenu === 'users'" class="content-section">
        <h1>用户列表</h1>
        <div class="actions">
          <button class="export-btn" @click="exportUsers">导出Excel</button>
          <button class="progress-btn" @click="startProgress">显示进度条</button>
        </div>
        
        <!-- 进度条 -->
        <div v-if="showProgress" class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
          </div>
          <div class="progress-text">{{ progress }}%</div>
        </div>
        
        <table v-if="users.length" class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>姓名</th>
              <th>邮箱</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.email }}</td>
            </tr>
          </tbody>
        </table>
        <p v-else>正在加载用户数据...</p>
      </div>

      <!-- 文件管理页面 -->
      <div v-if="activeMenu === 'files'" class="content-section">
        <h1>文件管理</h1>
        
        <!-- 文件上传区域 -->
        <div class="upload-section">
          <div class="upload-area">
            <input 
              type="file" 
              id="fileInput" 
              @change="handleFileUpload" 
              style="display: none;"
            />
            <label for="fileInput" class="upload-btn">
              📁 选择文件上传
            </label>
            <div class="upload-hint">
              <small>支持的文件大小: 最大10MB</small>
            </div>
          </div>
          
          <!-- 上传进度 -->
          <div v-if="uploadProgress > 0" class="upload-progress">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${uploadProgress}%` }"></div>
            </div>
            <div class="progress-text">上传进度: {{ uploadProgress }}%</div>
          </div>
          
          <!-- 消息提示 -->
          <div v-if="showUploadMessage" class="message-container" :class="messageType">
            <div class="message-content">
              <span class="message-icon">
                {{ messageType === 'success' ? '✅' : messageType === 'error' ? '❌' : '⚠️' }}
              </span>
              <span class="message-text">{{ uploadMessage }}</span>
            </div>
          </div>
        </div>

        <!-- OSS下载上传区域 -->
        <div class="oss-upload-section">
          <h3>OSS资源下载上传</h3>
          <div class="oss-upload-area">
            <div class="oss-input-group">
              <input 
                type="text" 
                v-model="ossUrl" 
                placeholder="请输入阿里云OSS资源地址"
                class="oss-url-input"
              />
              <button 
                @click="handleOssDownloadUpload" 
                class="oss-upload-btn"
                :disabled="ossUploadProgress > 0"
              >
                {{ ossUploadProgress > 0 ? '处理中...' : '下载并上传' }}
              </button>
            </div>
            <div class="oss-upload-hint">
              <small>支持从OSS下载文件并上传到MinIO存储</small>
            </div>
          </div>
          
          <!-- OSS上传进度 -->
          <div v-if="ossUploadProgress > 0" class="upload-progress">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${ossUploadProgress}%` }"></div>
            </div>
            <div class="progress-text">OSS下载上传进度: {{ ossUploadProgress }}%</div>
          </div>
          
          <!-- OSS消息提示 -->
          <div v-if="showOssUploadMessage" class="message-container" :class="ossMessageType">
            <div class="message-content">
              <span class="message-icon">
                {{ ossMessageType === 'success' ? '✅' : ossMessageType === 'error' ? '❌' : '⚠️' }}
              </span>
              <span class="message-text">{{ ossUploadMessage }}</span>
            </div>
          </div>
        </div>

        <!-- 文件列表 -->
        <div class="files-section">
          <h3>文件列表 (bucket-test1)</h3>
          <div v-if="files.length" class="files-grid">
            <div v-for="file in files" :key="file.name" class="file-card">
              <div class="file-icon">📄</div>
              <div class="file-info">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-details">
                  <span>大小: {{ formatFileSize(file.size) }}</span>
                  <span>修改时间: {{ formatDate(file.lastModified) }}</span>
                </div>
              </div>
              <div class="file-actions">
                <button class="action-btn download-btn" @click="downloadFile(file.name)">
                  下载
                </button>
                <button class="action-btn delete-btn" @click="deleteFile(file.name)">
                  删除
                </button>
              </div>
            </div>
          </div>
          <p v-else>暂无文件</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app-container {
  display: flex;
  height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 0;
  box-shadow: 2px 0 10px rgba(0,0,0,0.1);
}

.sidebar-header {
  padding: 0 20px 20px;
  border-bottom: 1px solid rgba(255,255,255,0.2);
  margin-bottom: 20px;
}

.sidebar-header h2 {
  font-size: 1.5rem;
  font-weight: 600;
}

.sidebar-nav {
  padding: 0 10px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  margin: 5px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-item:hover {
  background: rgba(255,255,255,0.1);
  transform: translateX(5px);
}

.nav-item.active {
  background: rgba(255,255,255,0.2);
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.nav-icon {
  font-size: 1.2rem;
  margin-right: 12px;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 30px;
  background: #f8f9fa;
  overflow-y: auto;
}

.content-section {
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  color: #333;
  margin-bottom: 30px;
  font-size: 2rem;
  font-weight: 600;
}

/* 按钮样式 */
.actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  gap: 10px;
}

.export-btn, .progress-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.export-btn:hover, .progress-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

/* 进度条样式 */
.progress-container, .upload-progress {
  margin: 20px 0;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e9ecef;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  margin-top: 8px;
  font-weight: 500;
  color: #666;
}

/* 表格样式 */
.data-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.data-table th, .data-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #e9ecef;
}

.data-table th {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.data-table tr:hover {
  background-color: #f8f9fa;
}

/* 文件管理样式 */
.upload-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.upload-area {
  text-align: center;
  padding: 40px;
  border: 2px dashed #667eea;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #764ba2;
  background: #f0f2ff;
}

.upload-btn {
  display: inline-block;
  padding: 15px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.upload-hint {
  margin-top: 10px;
  color: #666;
  font-size: 0.9rem;
}

/* 消息提示样式 */
.message-container {
  margin-top: 15px;
  padding: 12px 16px;
  border-radius: 6px;
  animation: slideIn 0.3s ease;
}

.message-container.success {
  background: #d4edda;
  border: 1px solid #c3e6cb;
  color: #155724;
}

.message-container.error {
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
}

.message-container.warning {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  color: #856404;
}

.message-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-icon {
  font-size: 1.1rem;
}

.message-text {
  flex: 1;
  font-size: 0.9rem;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.files-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.files-section h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 1.3rem;
}

.files-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.file-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.file-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.file-icon {
  font-size: 2rem;
  margin-right: 15px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  word-break: break-all;
}

.file-details {
  font-size: 0.9rem;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.download-btn {
  background: #28a745;
  color: white;
}

.download-btn:hover {
  background: #218838;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
  }
  
  .main-content {
    padding: 20px;
  }
  
  .files-grid {
    grid-template-columns: 1fr;
  }
}
</style>